package com.yun.zhong.fu.codelianxi.jmx;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.ManagementFactory;
import java.rmi.registry.LocateRegistry;

/**
 * @Author RenPu
 * @Date 2022/2/3 18:52
 * @Version 1.0
 * @Description:
 **/
public class JmxRegisterListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    JmxBean jmxBean;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event)  {
        try {
            MBeanServer server = ManagementFactory.getPlatformMBeanServer();

            ObjectName objectName=null;
             objectName = new ObjectName("jmxBean : name=testJM1X");
             server.registerMBean(jmxBean, objectName);
            LocateRegistry.createRegistry(1099);

            JMXServiceURL jmxServiceURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
            JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(jmxServiceURL, null, server);

            cs.start();

        } catch (Throwable e) {
            e.printStackTrace();
        }


    }
}
